package sk.naive.talker.command;

import sk.naive.talker.util.Utils;
import sk.naive.talker.persistence.PersistenceException;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.*;
import sk.naive.talker.message.DefaultMessageFactory;

import java.rmi.RemoteException;
import java.util.*;
import java.util.logging.Level;

/**
 * Setting of user's properties.
 *
 * <a href="mailto:maslenka@naive.deepblue.sk">Zuzana "Maslenka" Maslenova</a>
 * @version $Revision: 1.5 $ $Date: 2005/01/25 21:57:04 $
 */
public class UserSet extends AbstractSetCommand {
	private User victim;

	protected void permissionCheck() throws PermissionException, RemoteException {
		Utils.checkPermission(user, Consts.PERM_SUPERUSER);
	}

	public void exec()
		throws CommandException, RemoteException, PropertyStoreException
	{
		permissionCheck();
		String[] sa = Utils.splitWords(params, 2);
		if (sa.length < 1) {
			sendMisusageWarning();
			return;
		}
		victim = commandDispatcher.getUserFinder().findUserByLogin(sa[0]);
		if (victim == null) {
			sendUserNotFoundMessage(sa[0]);
			return;
		}
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "Victim", victim.getProperties());

		if (sa.length == 1) {
			user.send(showSettings());
		} else {
			params = sa[1];
			processParameters();
		}
	}

	protected String setValue(String key, String value)
		throws RemoteException,
		PropertyStoreException,
		PersistenceException
	{
		victim.set(key, victim.getProperty(key).toObject(value));
		logger().log(Level.INFO, "User {0} set property of user {1} property ''{2}'' to ''{3}''.", new Object[] {user.getLogin(), victim.getLogin(), key, value});
		return value;
	}

	protected Set<String> getValidValues(String key) throws RemoteException {
		return victim.getProperty(key).validValues();
	}

	protected String getValue(String key) throws RemoteException, PropertyStoreException {
		return victim.getProperty(key).toString(victim.get(key));
	}

	protected Set<String> settable() {
		return victim.getSettable();
	}

	protected void sendSetValueMessage(String value) throws RemoteException, CommandException {
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "Value", value);
		sendHelper().sendMessage(user, getSuccesfulSetKey());
		actionNotify(victim, "userSet.propSet");
	}

	protected String getHeaderKey() {
		return "userSet.head";
	}
}
